import axios, { AxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/store/auth'
import NProgress from 'nprogress'

interface RequestOptions extends AxiosRequestConfig {
  url: string;
  query?: any;
}

axios.interceptors.request.use((info: AxiosRequestConfig) => {
  NProgress.start()
  const authStore = useAuthStore()
  if (authStore.token) {
    info.headers.Authorization = `Basic ${authStore.token}`
  }
  return info
})

axios.interceptors.response.use((res) => {
  NProgress.done()
  return res
})

const request = async (options: RequestOptions): Promise<any> => {
  try {
    const resp = await axios({
      baseURL: '/api',
      ...options
    })
    if (resp.data.success) {
      return resp.data.data
    }
    return Promise.reject(new Error(resp.data.message))
  } catch (e) {
    return Promise.reject(new Error(`连接服务器错误：${e.message}`))
  }
}

export default request
